#-*- coding: utf-8 -*-
#! /usr/bin/python

import time
import sys
import os
from PAM30 import PAMIE
import win32api
import win32gui
import win32con
import ConfigParser
import datetime
import random
import hashlib

reload(sys)
sys.setdefaultencoding("utf-8")


def setRegValue1(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv==value):
            return True
        else:
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
            win32api.RegCloseKey(key)
            return True            
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def getRegValue1(keystr, vname):
    '''
    读取某个注册表项的值，返回值或者设置为1
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(str(kv)=="('no', 1)"):
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, '1')
            win32api.RegCloseKey(key)
            return "('1',1)"
        else:
            return kv            
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, '1')
        win32api.RegCloseKey(key)
        return True


def setRegValue(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv==value):
            return True
        else:
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
            win32api.RegCloseKey(key)
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def initConfig(filename):
    '''
    去掉文件头BOM等
    Window下用记事本打开配置文件并修改保存后，编码为UNICODE
    或UTF-8的文件的文件头
    #会被相应的加上\xff\xfe（\xff\xfe）或\xef\xbb\xbf
    '''
    import re
    content = open(filename).read()
    content = re.sub(r"\xfe\xff", "", content)
    content = re.sub(r"\xff\xfe", "", content)
    content = re.sub(r"\xef\xbb\xbf", "", content)
    open(filename, 'w').write(content)


def ordd(str):
    '''
    解决键盘码不对应问题,不知道别的电脑有没有这个问题
    '''
    t = ord(str)
    #65到90是A到Z
    if(t>90):
        return t-32
    else:
        return t


def typeme(passw):
    '''
    模拟人工输入,自动输入参数字符串到焦点窗口
    '''
    psht = len(passw)
    for j in range(psht):
        win32api.keybd_event(ordd(passw[j]), 0, 0, 0)
        time.sleep(0.5)
        win32api.keybd_event(ordd(passw[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(0.5)


def lgTaobao(username, userpass):
    '''
    使用指定用户名密码（在IE）登录淘宝
    '''
    #lgurl = 'http://i.taobao.com/my_taobao.htm?spm=a1z0e.3.217351.2.9fe82b&scm=1012.1.30.0'
    lgurl = 'https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm%3Fspm%3Da1z0e.3.217351.2.9fe82b%26scm%3D1012.1.30.0'
    ie.navigate(lgurl)
    ie.setTextBox('TPL_username', username.decode('utf-8'))
    ie.setCheckBox('J_SafeLoginCheck', 0)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    ie.clickElement(bt)
    ie.setTextBox('TPL_password', userpass)
    typeme(userpass)
    time.sleep(1.5)
    ie.clickElement(bt)
    if(ie.findText(username.decode('utf-8'))):
        return True
    else:
        return False


def jumpIEtab():
    '''
    跳转ctl+Tab,ie8的跳到下一个窗口的快捷键
    '''
    win32api.keybd_event(17, 0, 0, 0)#ctrl
    win32api.keybd_event(9, 0, 0, 0)#tab
    win32api.keybd_event(9, 0, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)


def CloseTab():
    '''
    跳转ctl+w,close当前窗口的快捷键
    '''
    win32api.keybd_event(17, 0, 0, 0)#ctrl
    win32api.keybd_event(87, 0, 0, 0)#w
    win32api.keybd_event(87, 0, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)


def logit(content, filename='log.txt'):
    '''
    逐行添加日志，每行一个回车
    头部是时间
    '''
    file = open(filename, 'a')
    try:
        timestr = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')+': '
        file.write(timestr+content+'\r\n')
    finally:
        file.close()


def getid(url):
    id = url.split('?id=')
    if(len(id)>1):
        id = (id[1].split('&'))[0]
        return id
    else:
        id = url.split('&id=')
        id = (id[1].split('&'))[0]
        return id


def goNextPage():
        try:
            next = ie.findElement('span', 'innerText', '下一页'.decode('utf8'))
            if(next):
                ie.clickLink(next)
                return True
        except:
            return False


def ctlClick(itemname):
    pdt = ie.findElement('a', 'title', itemname.decode('utf8'))
    #pdt = ie.findElement('a', 'title', itemname)
    win32api.keybd_event(17, 0, 0, 0)#ctrl
    ie.clickElement(pdt)
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(2)
    consis = str(pdt).find('tmall')
    if(consis == -1):
        ie.changeWindow((itemname+'-淘宝网').decode('utf8'))
    else:
        ie.changeWindow((itemname+'-tmall.com天猫').decode('utf8'))
    jumpIEtab()


def finditem(itemid, mtaoid):
    isFind = ie.findText(itemid)
    isFindt = ie.findText(mtaoid.decode('utf8'))
    if(isFind and isFindt):
        return True
    else:
        return False


def searchWd(sword, itemid, itemname, mtaoid, maxPage):
    '''
    根据提供的关键词进行搜索，遍历maxPage页寻找商品id
    '''
    ie.setTextBox('q', sword.decode('utf8'))
    ie.submitForm('search')
    time.sleep(2)
    page = 1
    find = False
    while(page<maxPage):
        if(finditem(itemid, mtaoid)):
            print 'get it'
            ctlClick(itemname)
            page = maxPage      
            find = True
            break            
        else:
            if(goNextPage()):
                page = page + 1
                print 'go page '+str(page)
                if(finditem(itemid, mtaoid)):
                    print 'get it'
                    ctlClick(itemname)
                    page = maxPage                    
                    find = True
                    break
            else:
                page = maxPage
                break                
    return find


def inputPass(passwd):
    '''
    模拟键盘输入密码
    passwd是一个list
    '''
    time.sleep(0.5)
    psht = len(passwd)
    for j in range(psht):
        if(ppass[j].isupper()):
            win32api.keybd_event(20, 0, 0, 0)#按下CAPS按键
            time.sleep(0.3)
            win32api.keybd_event(20, 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(0.3)
            win32api.keybd_event(ord(ppass[j]), 0, 0, 0)#按下按键
            time.sleep(0.3)
            win32api.keybd_event(ord(ppass[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(0.5)
            win32api.keybd_event(20, 0, 0, 0)#按下CAPS按键
            time.sleep(0.3)
            win32api.keybd_event(20, 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(0.4)
        else:
            win32api.keybd_event(ord(ppass[j]), 0, 0, 0)#按下按键
            time.sleep(0.3)
            win32api.keybd_event(ord(ppass[j]), 0, win32con.KEYEVENTF_KEYUP, 0)        
            time.sleep(0.4)


def pai(ppass, count):
        print 'kai pai'
        #设置数量
        #counttext = ie.findElement('input','id','J_IptAmount')
        ie.setTextBox('J_IptAmount', count)
        #拍下
        time.sleep(1.5)
        buy = ie.findElement('div', 'id', 'J_juValid')
        a = ie.getElementChildren(buy)
        b = ie.getElementChildren(a[0])
        eleArry = ie.getElementChildren(buy)
        ie.clickElement(b[0])
        time.sleep(2)
        #购买
        go = ie.findElement('a', 'id', 'J_Go')
        ie.clickElement(go)
        time.sleep(3)
        #到支付页面
        time.sleep(1.5)
        #回车
        win32api.keybd_event(13, 0, 0, 0)#按下按键
        time.sleep(0.3)
        win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0)        
        time.sleep(0.4)
        #点到输入框
        pp = ie.findElement('input', 'id', 'payPassword')
        ie.clickHiddenElement(pp)
        #先提交一下
        pay = ie.findElement('input', 'id', 'J_authSubmit')
        ie.clickElement(pay)
        time.sleep(1)
        #输入密码
        inputPass(ppass)
        ie.clickElement(pay)
        time.sleep(2)
        print '成功拍了一个\r\n'.decode('utf-8')


def pageDown():
    '''
    单纯按pagedown键，随机停留1-5秒
    '''
    win32api.keybd_event(34, 0, 0, 0)#pagedown
    time.sleep(0.5)
    win32api.keybd_event(34, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 3))


def pageUp():
    '''
    按pageUp键，随机停留1-3秒
    '''
    win32api.keybd_event(33, 0, 0, 0)#pageup
    time.sleep(0.5)
    win32api.keybd_event(33, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 2))


def endPage():
    '''
    end键，到页面底部
    '''
    win32api.keybd_event(35, 0, 0, 0)#edn
    time.sleep(0.5)
    win32api.keybd_event(35, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 2))


def homePage():
    '''
    home键，到页面顶部
    '''
    win32api.keybd_event(36, 0, 0, 0)#home
    time.sleep(0.5)
    win32api.keybd_event(36, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 3))


def clickBar():
    '''
    点击商品页面的信用详情页面
    '''
    bar = ie.findElement('ul', 'id', 'J_TabBar')
    bars = ie.getElementChildren(bar)
    ebar = ie.getElementChildren(bars[2])
    ie.clickElement(ebar[0])


def getMacAdd():
    '''
    获得mac地址
    '''
    import uuid
    node = uuid.getnode()
    mac = uuid.UUID(int = node).hex[-12:]
    return mac


def checksn(soft, sn):
    '''
    检查sn是否正常
    '''
    MAC = getMacAdd()
    #print makesn(soft, MAC)
    if(sn == makesn(soft, MAC)):        
        return True
    else:
        keystr = 'SOFTWARE\\Microsoft\\Internet Explorer\\Main'
        value = getRegValue1(keystr, 'Expand Alt Text')
        value = (str(value)).split("'")[1]        
        if(int(value)>=10):
            print 'Try times Out!! Please contact QQ:894610580 to buy'
            win32gui.MessageBox(0, '你的使用次数达到上限10次，请联系客服QQ:894610580购买！'.decode('utf-8'), 'Notice!', 0)
            return False
        else:
            value = str(int(value)+1)
            win32gui.MessageBox(0, '试用次数达到'+value+'次哦亲：）！'.decode('utf-8'), 'Notice!', 0)
            setRegValue1(keystr, 'Expand Alt Text', value)
            return True

        
def makesn(soft, MAC):
    '''
    soft是软件的发布版exe名字
    '''
    soft = soft + MAC
    x = hashlib.sha224((hashlib.md5('jhf')).hexdigest()+'jhfaixiaobao'+soft)
    return x.hexdigest()



def pageView():
    '''
    page down，go top ，view credit page
    view , go top
    '''
    win32api.keybd_event(122, 0, 0, 0)#f11
    win32api.keybd_event(122, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(random.randint(1, 4))
    t = random.randint(6, 15)
    i= 0
    while(i<t):
        pageDown()
        if(i>8 and i<11):
            pageUp()
        i = i+1
    endPage()
    clickBar()
    j = 0
    while(j<5):
        pageDown()
        if(j>2 and i<5):
            pageUp()
            time.sleep(random.randint(1, 2))
        time.sleep(random.randint(1, 3))
        j = j+1
    homePage()

#INI 文件大小不可改变
CONST_SIZE = 705

if(os.path.getsize('sys.ini')!=CONST_SIZE):
    win32gui.MessageBox(0, '试用版异常！'.decode('utf-8'), 'Notice!', 0)
    exit(0)


debug = False
#修改注册表,允许淘宝的弹出窗口
keystr = 'SOFTWARE\\Microsoft\\Internet Explorer\\New Windows\\Allow'
setRegValue(keystr, 's.taobao.com', '0')
if(debug):
    time.sleep(7)

#读取配置文件
config = ConfigParser.ConfigParser()
initConfig('sys.ini')
config.read('sys.ini')
username = config.get("global", "taobaoid")
userpass = config.get("global", "loginpass")
ppass = list(config.get("global", "paypass"))
maxPage = config.getint("global", "maxPage")
Mincount = config.getint("global", "Mincount")
buychance = config.getint("global", "buychance")
Maxcount = config.getint("global", "Maxcount")
mtaoid = config.get("global", "mtaoid")
sn = config.get("global", "sn")

if(debug):
    time.sleep(7)
#自动打开IE,进入我的淘宝
#自动输入用户名密码,登录淘宝,进入到我的淘宝
zhengban = checksn('cai', sn)
ie= PAMIE()
if(debug):
    time.sleep(7)
if(zhengban and lgTaobao(username, userpass)):    
    time.sleep(1)
    ie.navigate('http://www.taobao.com')
    #获取配置文件，转换为list
    itemcount = int(config.get("global", "itemcount"))
    wordlist = range(itemcount)
    itemlist = range(itemcount)
    namelist = range(itemcount)
    for i in range(itemcount):
        namelist[i] = config.get("names", "name"+str(i+1))
        wordlist[i] = config.get("words", "word"+str(i+1))
        itemlist[i] = config.get("items", "item"+str(i+1))
        itemid = getid(itemlist[i])
        rt = searchWd(wordlist[i], itemid, namelist[i], mtaoid, maxPage)
        if(debug):
            time.sleep(7)        
        if(rt):
            if(not debug):
                pageView()
            count = random.randint(Mincount, Maxcount)
            chance = random.randint(1, 100)
            if(chance<=buychance):
                if(debug):
                    time.sleep(7)                
                pai(ppass, str(count))
            ie.changeWindow((namelist[i]+'_淘宝搜索').decode('utf8'))
            CloseTab()
            ie.navigate('http://www.taobao.com')
    print 'OK,都已完成'
else:
    print '搜索不到目标页面或者软件未填写序列号'.decode('utf-8')
    if(debug):
        time.sleep(7)
    exit()

